import { Drawer, Button } from 'antd';
import { useState, useCallback, useRef } from 'react';
import clsx from 'clsx';
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import FormContent from '../FormContent';
import useFormValues from './useFormValues';

const titleMap = {
  add: '新增',
  modify: '修改',
  info: '详情',
};

export default function useInitDrawer({ title, maskClosable, closable, columns = 1, afterSubmit }) {
  const formRef = useRef(null);
  const [formType, setFormType] = useState(null);
  const [visible, setVisible] = useState(false);
  const [fullScreen, setFullScreen] = useState(false);

  const { data, getFormValues } = useFormValues();

  const open = useCallback(() => {
    setVisible(true);
  }, []);
  const close = useCallback(() => {
    setVisible(false);
    formRef.current && formRef.current.resetFields();
  }, []);
  const toggleFullScreen = useCallback(() => {
    setFullScreen(prev => !prev);
  }, []);
  const handleAfterSubmit = useCallback(() => {
    typeof afterSubmit === 'function' && afterSubmit();
    close();
  }, [afterSubmit, close]);

  return {
    visible,
    open,
    close,
    getFormValues,
    formType,
    setFormType,
    drawer: (
      <Drawer
        visible={visible}
        title={title || titleMap[formType]}
        maskClosable={maskClosable ?? formType === 'info'}
        closable={closable ?? formType === 'info'}
        bodyStyle={{ height: '100%', padding: 0 }}
        onClose={close}
        className={clsx({
          fullscreen: fullScreen,
          'drawer-big': columns > 1,
        })}
        extra={
          <Button type="link" shape="circle" onClick={toggleFullScreen}>
            {fullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
          </Button>
        }
      >
        <FormContent
          ref={formRef}
          onCancel={close}
          afterSubmit={handleAfterSubmit}
          formType={formType}
          data={data}
        />
      </Drawer>
    ),
  };
}
